//
//  CartViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/9/16.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "CartViewController.h"
#import "CartTableViewCell.h"
#import "ConfirmOrderViewController.h"
#import "PhoneRegisterViewController.h"
#import "CommonViewController.h"
#import "WeChatLoginViewController.h"
#import "MainViewController.h"
@interface CartViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)NSMutableArray * cellArr;
@property (nonatomic, assign)int currentPage;
@property (nonatomic, strong)NSString * codeString;//微信登录回调code
@property (nonatomic, strong)NSString * goodsID;//货物ID
@property (nonatomic, strong)NSString * cartID;//购物车ID
@property (nonatomic, strong)NSString * ifPay;//1为没交会员钱，0为已交会员钱
@property (nonatomic, assign)int deleteCell;//删除的哪一行
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * tokenString;
@property (nonatomic, assign)int presentTimes;//是否为modal回来后出来的页面
- (void)ifLogin;
@end

@implementation CartViewController(networkin)
//购物车数据
- (void)getCartData{
    NSDictionary * dic = @{
                           @"token":self.tokenString,
                           @"phone":self.phoneString,
                           @"page":@(self.currentPage),
                           @"size":@"6"
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"cartApi/iosindex" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            if (self.currentPage == 1) {
                [self.cellArr removeAllObjects];
            }
            [self.cellArr addObjectsFromArray:responseObject[@"list"][@"shopping"]];
            [self.tableView reloadData];
        }else if ([responseObject[@"sign"] isEqualToString:@"400"]){
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
//删除货物
- (void)deleteProdece{
    NSDictionary * dic = @{
                           @"token":self.tokenString,
                           @"phone":self.phoneString,
                           @"cartid":self.cartID
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"cartApi/iosdeleteshoppingcar" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [self.cellArr removeObjectAtIndex:self.deleteCell];
            [self.tableView reloadData];
        }else if ([responseObject[@"sign"] isEqualToString:@"400"]){
            ShowMessage(responseObject[@"msg"]);
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}
@end
@implementation CartViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.view addSubview:self.tableView];
    self.currentPage = 1;
    if ([[UserModel sharedInstanced].token isEqualToString:@""] || [UserModel sharedInstanced].token == nil || [[UserModel sharedInstanced].token length] == 0 || [[UserModel sharedInstanced].mobile isEqualToString:@""] || [UserModel sharedInstanced].mobile == nil || [[UserModel sharedInstanced].mobile length] == 0) {
        self.tokenString = @"";
        self.phoneString = @"";
    }else{
        self.tokenString = [UserModel sharedInstanced].token;
        self.phoneString = [UserModel sharedInstanced].mobile;
    }
    [self getCartData];//网络接口
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}
#pragma mark - init
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - TABBAR_HEIGHT - NAVI_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 160/WIDTH_6_SCALE;;
        [_tableView registerClass:[CartTableViewCell class] forCellReuseIdentifier:NSStringFromClass([CartTableViewCell class])];
        _tableView.backgroundColor = getColor(mainColor);
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.currentPage = 1;
            [self getCartData];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            self.currentPage ++;
            [self getCartData];
        }];
    }return _tableView;
}
- (NSMutableArray *)cellArr{
    if (!_cellArr) {
        _cellArr = @[].mutableCopy;
    }return _cellArr;
}
#pragma mark - tableViewDelegate和tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof (self)weakSelf = self;
    CartTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CartTableViewCell class]) forIndexPath:indexPath];
    cell.model = self.cellArr[indexPath.row];
    cell.deleteProduceBlock = ^(NSString * _Nonnull cartID) {
        weakSelf.cartID = cartID;
        self.deleteCell = (int)indexPath.row;
        [weakSelf deleteProdece];
    };
    cell.listDetailBlock = ^(NSString * _Nonnull cartID, NSString * _Nonnull goodssum) {
        ConfirmOrderViewController * vc = [[ConfirmOrderViewController alloc] init];
        vc.produceID = cartID;
        vc.addressID = @"0";
        vc.produceNum = goodssum;
        vc.fromWhcichController = @"CartViewController";
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    };
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cellArr.count;
}
#pragma mark - action
- (void)ifLogin{
    WeChatLoginViewController * vc = [[WeChatLoginViewController alloc] init];
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc];
    vc.backHomePageBlock = ^{
        [vc dismissViewControllerAnimated:YES completion:nil];
        [self.tabBarController setSelectedIndex:0];
        [self.navigationController popToRootViewControllerAnimated:YES];
    };
//    vc.beThereThePageBlock = ^{
//        [vc dismissViewControllerAnimated:YES completion:nil];
//        MainViewController *mainVc = [[MainViewController alloc] init];
//        [UIApplication sharedApplication].keyWindow.rootViewController =mainVc;
//        [self.tabBarController setSelectedIndex:2];
//    };
    [self presentViewController:navi animated:YES completion:nil];
}
@end
